<template>
<div>
    <h2 class="sub-header">Hero List</h2>
    <a class="btn btn-success" href="add.html" @click.prevent="addItem()">Add</a>
    <div class="table-responsive">
        <table class="table table-striped">
            <thead>
                <tr>
                    <th>#</th>
                    <th>姓名</th>
                    <th>性别</th>
                    <th>操作</th>
                </tr>
            </thead>
            <tbody>
                <tr v-for="(item,index) in list" :key="index">
                    <td>{{item.id}}</td>
                    <td>{{item.name}}</td>
                    <td>{{item.gender}}</td>
                    <td>
                        <a href="edit.html"
                        @click.prevent="editHtml(item.id)" >编辑</a> &nbsp;&nbsp;
                        <a
                        href="javascript:window.confirm('Are you sure?')"
                        @click.prevent="deleItem(item.id)"
                        >删除</a>
                    </td>
                </tr>
            </tbody>
        </table>
    </div>
</div>
</template>

<script>
// 引入axios
// import axios from 'axios'
export default {
  // 选项
  data() {
    return {
      list: []
    }
  },
  // 钩子函数(生命周期)
  mounted() {
    this.loadListData()
  },
  methods: {
    // 显示编辑页面
    editHtml(heroID) {
      // id -> 2
      // js修改url
      this.$router.push('/edit/' + heroID)
    },

    // 添加->渲染添加页面->Add.vue<-url
    addItem() {
      // 通过js代码修改标识 /add
      // router-link 改标识
      // router.push()
      this.$router.push({ path: '/add' })
    },
    // 删除
    deleItem(heroID) {
      // 提示框
      if (confirm('Sure?')) {
        // 删除->axios.delete()
        this.$http.delete('heroes/' + heroID).then(res => {
          // 更新视图
          this.loadListData()
        })
      }
      return
    },

    // 获取英雄列表的数据
    loadListData() {
      this.$http.get('heroes').then(res => {
        const { status, data } = res
        if (status === 200) {
          // data
          // console.log(data)
          this.list = data
          // console.log(this.list)
        }
      })
    }
  }
}
</script>

<style>
</style>
